<template>
  <div class="dept-page page-main">
    <div class="table-toolbar">
      <add-button @click="add()" />
    </div>
    <g-table
      ref="tableRef"
      row-key="deptId"
      :columns="columns"
      :api="getDeptList"
      :params="searchParams"
      :pagination="false"
    />

    <DeptDetail v-model:visible="visible" :data="activeRow" @change="search(false)" />
  </div>
</template>

<script setup lang="tsx">
import { getDeptList, deleteDept } from '@/api/dept'
import type { IDept } from '@/types/dept';
import DeptDetail from './detail.vue'

const searchParams = reactive({
  username: ''
})

let visible = $ref(false)

const { tableRef, columns, search } = useTable<IDept>([
  { title: '部门名称', dataIndex: 'name' },
  { title: '部门ID', dataIndex: 'deptId' },
  { title: '上级部门', dataIndex: 'parentName' },
  { title: '排序', dataIndex: 'orderNum' },
  {
    title: '操作',
    dataIndex: 'op',
    customRender: ({ record }) => (
      <>
        <table-button onClick={() => add(record)}>编辑</table-button>
        <confirm-button danger onClick={() => remove(record)}>删除</confirm-button>
      </>
    )
  }
])

let activeRow = $ref<Partial<IDept>>({})
function add(row: Partial<IDept> = {}) {
  activeRow = {...row}
  visible = true
}

function remove({ deptId }: IDept) {
  deleteDept(deptId as number).then(() => {
    AntMessage.success('已删除')
    search(false)
  })
}
</script>

<style lang="less"></style>